package com.lighting.smssystem.aspect;

import com.lighting.smssystem.constrants.RoleRel;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.utils.ThreadContext;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Author LeeMaster
 */
@Aspect
@Slf4j
@Component
@ConditionalOnProperty(prefix = "system",name = "auth",havingValue = "true")
public class RoleAspect {

    @Pointcut(value = "@annotation(com.lighting.smssystem.aspect.RequireRole)")
    public void roleAspect(){}

    private void handleOrRoles(UserRole role,UserRole[] roles)throws RoleAccessException{

        if(Arrays.asList(roles).contains(role)){
            log.info("通过鉴权");
            return ;
        }
        log.info("鉴权失败");
        throw new RoleAccessException("无权限调用本接口");
    }


    @Around("roleAspect()")
    public Object processAspect(ProceedingJoinPoint joinPoint) throws Throwable {

        UserRole currentRole = ThreadContext.getRole();

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        RequireRole requireRole =  methodSignature.getMethod().getAnnotation(RequireRole.class);

        log.info("[User {} with role {} to access method {}]",ThreadContext.getName(),currentRole,methodSignature.getMethod().getName());

        if(requireRole.rel() == RoleRel.OR){
            handleOrRoles(currentRole,requireRole.role());
            return joinPoint.proceed();
        }else{
            throw new RoleAccessException("无权限调用本接口");
        }
    }
}
